package doInterce.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import doInterce.DoInterface;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import utils.DBUtil;
import utils.ExceptionUtil;
import utils.YearUtil;
import utils.YmlUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.*;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 查询报表并生成excel
 * @Author: syh
 */
public class DoQueryReport implements DoInterface {
    @Override
    public void doExecute() {
        try {
            Map<String, Object> ymlMap = YmlUtil.getYmlMap();
            String url = Convert.toStr(ymlMap.get("url"));
            String userName = Convert.toStr(ymlMap.get("userName"));
            String password = Convert.toStr(ymlMap.get("password"));

            start(DBUtil.getConnection(url, userName, password));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(Connection conn) throws SQLException {
        List<String> nameAList = new ArrayList<>();
        Map<String,String> tableMap = new HashMap<>();
        // 创建一个 JFrame 实例
        JFrame frame = new JFrame("报表查询（公务员）S");

        // 创建标签、输入框、下拉框、文本框和按钮
        JLabel yearLabel = new JLabel("年报年份（公）:");
        Object[] yearArr = YearUtil.getYear();
        String[] yearOptions = (String[])yearArr[0];

//        String[] yearOptions = {"2023" ,"2022"};
        JComboBox<String> yearComboBox = getComboBox(yearOptions,300,30);
        if(yearArr[1] != null){
            String defaultYear = (String)yearArr[1];
            yearComboBox.setSelectedIndex(ArrayUtil.indexOf(yearOptions,defaultYear));
        }


        JLabel unitLabel = new JLabel("单位名称（公）:");
        JTextField unitText = getInput(370,30);

        JLabel typeLabel = new JLabel("报表类型（公）:");
        String[] typeOptions = {"(1)公务员统计表" ,"(2)参照公务员法管理的群团机关工作人员统计表","(3)参照公务员法管理的事业单位工作人员统计表"};
        JComboBox<String> typeComboBox = getComboBox(typeOptions,300,30);

        JLabel outModelLabel = new JLabel("输出模式（公）:");
        JRadioButton yes = new JRadioButton("混合");
        JRadioButton no = new JRadioButton("分开");
        no.setPreferredSize(new Dimension(310, 30));

        JLabel nameLabel = new JLabel("报表名称（一）:");
        JComboBox<String> nameComboBox = getComboBox(new String[]{},300,30);
        JLabel nameLabelB = new JLabel("报表名称（二）:");
        JComboBox<String> nameComboBoxB = getComboBox(new String[]{},370,30);

        JLabel rowLabel = new JLabel("报表行数（一）:");
        JTextField rowText = getInput(300,30);
        JLabel rowLabelB = new JLabel("报表行数（二）:");
        JTextField rowTextB = getInput(370,30);

        JLabel colLabel = new JLabel("报表列数（一）:");
        JTextField colText = getInput(300,30);
        JLabel colLabelB = new JLabel("报表列数（二）:");
        JTextField colTextB = getInput(370,30);


        JLabel outLabel = new JLabel("日志输出（公）:");
        JTextArea outArea = getTextArea(890,50);
        JButton button = new JButton("开始执行");
        JButton openFileButton = new JButton("打开文件");

        getNameList(conn, yearComboBox, typeComboBox, nameComboBox,nameComboBoxB, nameAList, tableMap);

        ButtonGroup group = new ButtonGroup();
        group.add(yes);
        yes.setSelected(true);
        group.add(no);


        // 创建面板并添加组件
        JPanel panel = new JPanel();
        panel.add(yearLabel);
        panel.add(yearComboBox);

        panel.add(unitLabel);
        panel.add(unitText);

        panel.add(typeLabel);
        panel.add(typeComboBox);
        panel.add(outModelLabel);
        panel.add(yes);
        panel.add(no);

        panel.add(nameLabel);
        panel.add(nameComboBox);
        panel.add(nameLabelB);
        panel.add(nameComboBoxB);

        panel.add(rowLabel);
        panel.add(rowText);
        panel.add(rowLabelB);
        panel.add(rowTextB);

        panel.add(rowLabel);
        panel.add(rowText);
        panel.add(rowLabelB);
        panel.add(rowTextB);

        panel.add(colLabel);
        panel.add(colText);
        panel.add(colLabelB);
        panel.add(colTextB);


        panel.add(outLabel);
        JScrollPane outAreaScrollPane = new JScrollPane(outArea);
        panel.add(outAreaScrollPane);

        panel.add(button);
        panel.add(openFileButton);


        /**
         * 开始执行的点击事件
         */
        button.addActionListener(e -> {
            outArea.setText("");

            //收集页面数据
            QueryInfo queryInfo = new QueryInfo();
            queryInfo.setYear(yearComboBox.getSelectedItem()+"");
            queryInfo.setUnit(unitText.getText().trim());
            queryInfo.setType(typeComboBox.getSelectedItem()+"");
            queryInfo.setNameA(nameComboBox.getSelectedItem()+"");
            queryInfo.setRowA(rowText.getText().trim().replaceAll("   ", " ").replaceAll("  ", " "));
            queryInfo.setColA(colText.getText().trim().replaceAll("   ", " ").replaceAll("  ", " "));

            queryInfo.setNameB(nameComboBoxB.getSelectedItem()+"");
            queryInfo.setRowB(rowTextB.getText().trim().replaceAll("   ", " ").replaceAll("  ", " "));
            queryInfo.setColB(colTextB.getText().trim().replaceAll("   ", " ").replaceAll("  ", " "));
            queryInfo.setOutModel(yes.isSelected() ? "1":"2");

            outArea.append("开始信息校验\n");
            //校验数据
            try {
                String tip = verifyQueryInfo(queryInfo, conn,tableMap);
                if(StrUtil.isNotEmpty(tip)){
                    outArea.append(tip+"\n");
                    JOptionPane.showMessageDialog(null, tip, "错误", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }

                List<ExcelTitleInfo> headList = new ArrayList<>();
                List<List<String>> dataList = startFind(queryInfo, conn, outArea, yearComboBox, typeComboBox,headList);
                outArea.append("查找完成\n");
                String path = writeExcel(headList, dataList,outArea);
                outArea.append("输出地址==="+path+"\n");


            }catch (Exception exception) {
                outArea.append("出现异常，程序已经终止！\n");
                JOptionPane.showMessageDialog(null, "校验过程出错！"+exception.getMessage(), "错误", JOptionPane.INFORMATION_MESSAGE);
                ExceptionUtil.writeLog(exception);

                return;
            }
            outArea.append("程序完成\n");

        });


        /**
         * 开始执行的点击事件
         */
        openFileButton.addActionListener(e -> {
            String text = outArea.getText();
            String[] split = text.split("\n");
            for(String str : split){
                if(str.startsWith("输出地址===")){
                    try {
                        Desktop.getDesktop().open(new File(str.split("===")[1]));
                        return;
                    }catch (Exception exception) {
                        JOptionPane.showMessageDialog(null, "打开文件出错！"+exception.getMessage(), "错误", JOptionPane.INFORMATION_MESSAGE);
                        ExceptionUtil.writeLog(exception);
                        return;
                    }
                }
            }

            JOptionPane.showMessageDialog(null, "没有找到输出文件！", "错误", JOptionPane.INFORMATION_MESSAGE);
            return;
        });

        /**
         * 切换报表类型
         */
        typeComboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    try {
                        getNameList(conn, yearComboBox, typeComboBox, nameComboBox,nameComboBoxB, nameAList, tableMap);
                    }catch (Exception exception) {
                        outArea.append("出现异常，程序已经终止！\n");
                        JOptionPane.showMessageDialog(null, "获取表名出错！"+exception.getMessage(), "错误", JOptionPane.INFORMATION_MESSAGE);
                        ExceptionUtil.writeLog(exception);
                    }
                }
            }
        });

        /**
         * 切换年份
         */
        yearComboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    try {
                        getNameList(conn, yearComboBox, typeComboBox, nameComboBox,nameComboBoxB, nameAList, tableMap);
                    }catch (Exception exception) {
                        outArea.append("出现异常，程序已经终止！\n");
                        JOptionPane.showMessageDialog(null, "获取表名出错！"+exception.getMessage(), "错误", JOptionPane.INFORMATION_MESSAGE);
                        ExceptionUtil.writeLog(exception);
                    }
                }
            }
        });


        // 将面板添加到框架中
        frame.add(panel);

        // 设置框架属性
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(950, 500);
        frame.setVisible(true);
    }

    /**
     * 根据年份和类型获取表名
     * @param conn
     * @param yearComboBox 年份组件
     * @param typeComboBox 类型组件
     * @param nameComboBox 表名组件
     * @param nameAList 表名列表
     * @param tableMap
     * @throws SQLException
     */
    public void  getNameList(Connection conn,JComboBox<String> yearComboBox,JComboBox<String> typeComboBox,JComboBox<String> nameComboBox,JComboBox<String> nameComboBoxB,List<String> nameAList,Map<String,String> tableMap) throws SQLException {
        String reportTableName = getTableId(yearComboBox, typeComboBox);


        nameAList.clear();
        tableMap.clear();
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("select TABLEID,RPTID,TABLENAME from TABLEINFO where RPTID='" + reportTableName + "' and TABLEYEAR='" + yearComboBox.getSelectedItem() + "' order by TABLEID");
        while (resultSet.next()){
            nameAList.add(resultSet.getString(3));
            tableMap.put(resultSet.getString(3),resultSet.getString(1));
        }

        resultSet.close();
        statement.close();


        nameComboBox.removeAllItems();
        for (String s : nameAList) {
            nameComboBox.addItem(s);
        }
        nameComboBoxB.removeAllItems();
        for (String s : nameAList) {
            nameComboBoxB.addItem(s);
        }

    }

    /**
     * 拼凑报表数据所在的表
     * @param yearComboBox
     * @param typeComboBox
     * @throws SQLException
     */
    public String  getTableId(JComboBox<String> yearComboBox,JComboBox<String> typeComboBox) throws SQLException {
        String reportTableName = "J"+(yearComboBox.getSelectedItem()+"").substring(2)+getTypeCode(typeComboBox.getSelectedItem()+"");

        return  reportTableName;
    }

    /**
     * 开始对比有差距的单位
     * @param queryInfo
     * @param conn
     * @param outArea
     * @param headList 表头
     * @throws SQLException
     */
    public List<List<String>> startFind(QueryInfo queryInfo, Connection conn,JTextArea outArea,JComboBox<String> yearComboBox,JComboBox<String> typeComboBox,List<ExcelTitleInfo> headList) throws Exception {
        String reportTableNameA = getTableId(yearComboBox, typeComboBox);
        String reportTableNameB = getTableId(yearComboBox, typeComboBox);


        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("select id from tj_un where rptyear='" + queryInfo.getYear() + "' and name='" + queryInfo.getUnit() + "'");
        //机构编码
        String unitId = DBUtil.getStringValue(resultSet, null);
        resultSet.close();

        String[] rowsIdSqlArr = getRowsIdSql(queryInfo,outArea);
        String selectFieldSql = getSelectFieldSql(queryInfo, headList);
        //查找所有报表数据
        String tableASql = "SELECT *,(@row_number:=CASE WHEN @prevA0000=UNITID THEN @row_number+1 ELSE 1 END) row_num, @prevA0000:=UNITID FROM "+reportTableNameA+", (SELECT @row_number:=0, @prevA0000:='') AS t  "+" where ROWSID in ("+ rowsIdSqlArr[0] +") and TABLEID='"+queryInfo.getNameA()+"' ORDER BY UNITID, rowsid";
        String tableBSql = "SELECT *,(@row_number:=CASE WHEN @prevA0000=UNITID THEN @row_number+1 ELSE 1 END) row_num, @prevA0000:=UNITID FROM "+reportTableNameB+", (SELECT @row_number:=0, @prevA0000:='') AS t  "+" where ROWSID in ("+ rowsIdSqlArr[1] +") and TABLEID='"+queryInfo.getNameB()+"' ORDER BY UNITID, rowsid";
        String reportSql = "select t3.name,"+selectFieldSql+" from ("+tableASql+") t1 inner join ("+tableBSql+") t2 on t1.UNITID=t2.UNITID and t1.row_num=t2.row_num inner join (select * from tj_un where RPTYEAR='"+queryInfo.getYear()+"') t3 on t1.unitid=t3.id where t1.unitid in (select UNID from M_M01 where UNID like '"+unitId+"%' and (M0104 is null or M0104='"+queryInfo.getType().replaceAll("0", "")+"')) order by t1.UNITID,t1.row_num";
        if("1".equalsIgnoreCase(queryInfo.getIsOne())){  //单表查询
            reportSql = "select t3.name,"+selectFieldSql+" from ("+tableASql+") t1 inner join (select * from tj_un where RPTYEAR='"+queryInfo.getYear()+"') t3 on t1.unitid=t3.id where t1.unitid in (select UNID from M_M01 where UNID like '"+unitId+"%' and (M0104 is null or M0104='"+queryInfo.getType().replaceAll("0", "")+"')) order by t1.UNITID,t1.row_num";
        }
        outArea.append("报表查询语句："+reportSql+"\n");

        Statement reportStatement = conn.createStatement();
        ResultSet reportRs = reportStatement.executeQuery(reportSql);
        List<List<String>> dataList = new ArrayList<>();
        ResultSetMetaData metaData = reportRs.getMetaData();
        List<String> titleList = new ArrayList<>();
        titleList.add("单位名称");
        for(int i = 2 ; i <= metaData.getColumnCount(); i++){
            titleList.add(metaData.getColumnName(i));
        }
        outArea.append("查找表头结束\n");
        while (reportRs.next()){
            List<String> eleList = new ArrayList<>();
            eleList.add(reportRs.getString(1));
            for(int i = 2 ; i <= metaData.getColumnCount(); i++){
                eleList.add(Convert.toStr(reportRs.getString(i),""));
            }
            dataList.add(eleList);
        }
        outArea.append("查找数据结束\n");
        reportRs.close();
        reportStatement.close();

        return dataList;
    }

    /**
     * 获取select 字段
     * @param queryInfo
     * @param headList
     * @return
     */

    public String getSelectFieldSql(QueryInfo queryInfo,List<ExcelTitleInfo> headList){
        String colA = queryInfo.getColA();
        String colB = queryInfo.getColB();

        String[] colArrA = null;
        if(colA.contains(",")){
            colArrA = colA.split(",");
        }else{
            colArrA = colA.split(" ");
        }
        for(int i = 0 ; i < colArrA.length ; i++){
            colArrA[i] = StrUtil.isNotBlank(colArrA[i]) ? colArrA[i].trim() : colArrA[i];
        }

        String[] colArrB = null;
        if(colB.contains(",")){
            colArrB = colB.split(",");
        }else{
            colArrB = StrUtil.isBlank(colB) ? new String[]{} :colB.split(" ");
        }
        for(int i = 0 ; i < colArrB.length ; i++){
            colArrB[i] = StrUtil.isNotBlank(colArrB[i]) ? colArrB[i].trim() : colArrB[i];
        }


        headList.add(new ExcelTitleInfo("单位名称",1));
        if("1".equalsIgnoreCase(queryInfo.outModel)){
            List<String> mergedList = new ArrayList<>();
            int maxLength = Math.max(colArrA.length, colArrB.length);
            for (int i = 0; i < maxLength; i++) {
                if (i < colArrA.length) {
                    mergedList.add("T1.J"+colArrA[i]+" as T1_J"+colArrA[i]);
                    headList.add(new ExcelTitleInfo("T1_J"+colArrA[i],i % 2));
                }
                if (i < colArrB.length) {
                    mergedList.add("T2.J"+colArrB[i]+" as T2_J"+colArrB[i]);
                    headList.add(new ExcelTitleInfo("T2_J"+colArrB[i],i % 2));
                }
            }
            return CollectionUtil.join(mergedList,",");
        }else{
            List<String> mergedList = new ArrayList<>();
            for (int i = 0; i < colArrA.length; i++) {
                mergedList.add("T1.J"+colArrA[i]+" as T1_J"+colArrA[i]);
                headList.add(new ExcelTitleInfo("T1_J"+colArrA[i],0));
            }
            for (int i = 0; i < colArrB.length; i++) {
                mergedList.add("T2.J"+colArrB[i]+" as T2_J"+colArrB[i]);
                headList.add(new ExcelTitleInfo("T1_J"+colArrB[i],1));

            }
            return CollectionUtil.join(mergedList,",");
        }

    }

    /**
     * 获取行
     * @param queryInfo
     * @return
     */
    public String[] getRowsIdSql(QueryInfo queryInfo,JTextArea outArea) throws Exception {
        String rowA = queryInfo.getRowA();
        String rowB = queryInfo.getRowB();

        String[] rowArrA = null;
        if(rowA.contains(",")){
            rowArrA = rowA.split(",");
        }else{
            rowArrA = rowA.split(" ");
        }

        String[] rowArrB = null;
        if(rowB.contains(",")){
            rowArrB = rowB.split(",");
        }else{
            rowArrB = StrUtil.isBlank(rowB) ? new String[]{} :rowB.split(" ");
        }

        if(rowArrB.length > 0 && rowArrA.length != rowArrB.length){
            throw new Exception("报表一和报表二的行数的总数应该保持一致\n");
        }
        String whereA = Arrays.stream(rowArrA).map(ele -> StrUtil.isNotBlank(ele) ? ele.trim() : ele).collect(Collectors.joining(","));
        String whereB = Arrays.stream(rowArrB).map(ele -> StrUtil.isNotBlank(ele) ? ele.trim() : ele).collect(Collectors.joining(","));

        return new String[]{whereA,whereB};
    }


    public static JTextField getInput(int width,int height) {
        JTextField textField = new JTextField(); // 10 是文本框的列数，可以调整文本框的宽度
        textField.setPreferredSize(new Dimension(width, height)); // 设置文本框的宽度和高度

        return textField;
    }

    public static JComboBox getComboBox(String[] typeOptions,int width,int height) {
        JComboBox<String> comboBox = new JComboBox<>(typeOptions);
        comboBox.setPreferredSize(new Dimension(width, height));
        return comboBox;
    }

    public static JTextArea getTextArea(int width,int height) {
        JTextArea textArea = new JTextArea(10, 70);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        return textArea;
    }


    /**
     * 验证填写的信息是否正确
     * @param queryInfo
     * @return
     */
    public String verifyQueryInfo(QueryInfo queryInfo,Connection conn,Map<String,String> tableMap) throws SQLException {
        if(StrUtil.isBlank(queryInfo.getYear()) || "null".equals(queryInfo.getYear())){
            return "年份没有填写!";
        }
        if(StrUtil.isBlank(queryInfo.getUnit())){
            return "单位名称没有填写!";
        }
        if(StrUtil.isBlank(queryInfo.getType()) || "null".equals(queryInfo.getType())){
            return "查询报表类型（一）没有填写!";
        }
        if(StrUtil.isBlank(queryInfo.getNameA()) || "null".equals(queryInfo.getNameA())){
            return "报表名称（一）没有填写!";
        }
        if(StrUtil.isBlank(queryInfo.getRowA())){
            return "报表行数（一）没有填写!";
        }
        if(StrUtil.isBlank(queryInfo.getColA())){
            return "报表列数（一）没有填写!";
        }

//        if(StrUtil.isBlank(queryInfo.getNameB()) || "null".equals(queryInfo.getNameB())){
//            return "报表名称（二）没有填写!";
//        }
//        if(StrUtil.isBlank(queryInfo.getRowB())){
//            return "报表行数（二）没有填写!";
//        }
        if(StrUtil.isNotBlank(queryInfo.getRowB()) && StrUtil.isBlank(queryInfo.getColB())){
            return "报表列数（二）没有填写，如果需要查询单表，需要把表二的行列都清空!";
        }

        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("select count(1) cut from tj_un where rptyear='" + queryInfo.getYear() + "' and name='" + queryInfo.getUnit() + "'");
        if(resultSet.next()){
            if(resultSet.getInt(1) == 0){
                return "没有找到该单位，请检查是否填写和系统的一致!";
            }
            if(resultSet.getInt(1) > 1){
                return "系统有多个重名的单位，无法继续查询!";
            }
        }
        resultSet.close();
        statement.close();

        String typeCode = getTypeCode(queryInfo.getType());
        queryInfo.setType(typeCode);
        if(StrUtil.isBlank(typeCode)){
            return "报表类型（一）没有找到该报表类型!";
        }


        queryInfo.setNameA(tableMap.get(queryInfo.getNameA()));
        queryInfo.setNameB(tableMap.get(queryInfo.getNameB()));

        if(StrUtil.isBlank(queryInfo.getColB())){
            queryInfo.setIsOne("1");
        }else{
            queryInfo.setIsOne("0");
        }
        if(!queryInfo.getRowA().replaceAll(",", "").replaceAll(" ", "").matches("\\d+")){
            return "报表行数（一）不是数字!";
        }
        if(!queryInfo.getColA().replaceAll(",", "").replaceAll(" ", "").matches("\\d+")){
            return "报表列数（一）不是数字（分隔符支持英文逗号和空格）!";
        }
        if(StrUtil.isNotBlank(queryInfo.getRowB()) && !queryInfo.getRowB().replaceAll(",", "").replaceAll(" ", "").matches("\\d+")){
            return "报表行数（二）不是数字!";
        }
        if(StrUtil.isNotBlank(queryInfo.getColB()) && !queryInfo.getColB().replaceAll(",", "").replaceAll(" ", "").matches("\\d+")){
            return "报表列数（二）不是数字（分隔符支持英文逗号和空格）!";
        }

        return null;
    }


    /**
     * 查找报表类型编码
     * @param name
     * @return
     */
    public String getTypeCode(String name){
        Map<String,String> nameMap = new HashMap<>();
        nameMap.put("(1)公务员统计表","01");
        nameMap.put("(2)参照公务员法管理的群团机关工作人员统计表","02");
        nameMap.put("(3)参照公务员法管理的事业单位工作人员统计表","03");

        return nameMap.get(name);
    }

    public String writeExcel(List<ExcelTitleInfo> headList,List<List<String>> contentList,JTextArea outArea){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");
        XSSFRow row = sheet.createRow(0);

        XSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(IndexedColors.LIME.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        sheet.setDefaultColumnWidth(30);
        outArea.append("开始设置表头，"+headList.size()+","+contentList.size()+"\n");
        /**
         * 设置表头
         */
        for(int i = 0 ; i < headList.size(); i++){
            ExcelTitleInfo titleEle = headList.get(i);
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(titleEle.getTitle());
            if(titleEle.getColor() == 1){
                cell.setCellStyle(style);
            }else{
                cell.setCellStyle(style2);
            }
        }
        outArea.append("设置表头结束\n");
        for(int i = 0 ; i < contentList.size(); i++){
            List<String> eleList = contentList.get(i);
            XSSFRow eleRow = sheet.createRow(i+1);

            for(int j = 0 ; j < eleList.size(); j++){
                XSSFCell cell = eleRow.createCell(j);
                cell.setCellValue(eleList.get(j));
                if(headList.get(j).getColor() == 1){
                    cell.setCellStyle(style);
                }else{
                    cell.setCellStyle(style2);
                }
            }
        }
        outArea.append("设置数据结束\n");
        String path = "";
        //输出Excel
        try {
            File dFile = new File("D:\\");
            if(dFile.exists()){
                File file = new File("D:\\自定义查询结果_" + System.currentTimeMillis() + ".xlsx");
                path = file.getAbsolutePath();
            }else{
                File file = new File("C:\\自定义查询结果_" + System.currentTimeMillis() + ".xlsx");
                path = file.getAbsolutePath();
            }
            outArea.append("获取文件位置结束，地址："+path+"\n");
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            workbook.write(fileOutputStream);
            workbook.close();
            fileOutputStream.close();
            outArea.append("输出到文件结束\n");
        }
        catch (Exception e){
            outArea.append("出现异常，"+e.getMessage()+"\n");
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "保存到文件出错！"+e.getMessage(), "错误", JOptionPane.INFORMATION_MESSAGE);
            ExceptionUtil.writeLog(e);
        }

        return path;
    }

    class ExcelTitleInfo{
        private String title;
        private int color;

        public ExcelTitleInfo() {
        }

        public ExcelTitleInfo(String title, int color) {
            this.title = title;
            this.color = color;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }
    }
    /**
     * 查询信息
     */
    class QueryInfo{
        private String year;
        private String unit;
        private String type;
        private String nameA;
        private String nameB;
        private String rowA;
        private String rowB;
        private String colA;
        private String colB;

        private String outModel;
        private String output;

        //是否只需要一个表
        private String isOne;

        public QueryInfo() {
        }

        public String getYear() {
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public String getUnit() {
            return unit;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }


        public String getNameA() {
            return nameA;
        }

        public void setNameA(String nameA) {
            this.nameA = nameA;
        }

        public String getNameB() {
            return nameB;
        }

        public void setNameB(String nameB) {
            this.nameB = nameB;
        }

        public String getRowA() {
            return rowA;
        }

        public void setRowA(String rowA) {
            this.rowA = rowA;
        }

        public String getRowB() {
            return rowB;
        }

        public void setRowB(String rowB) {
            this.rowB = rowB;
        }

        public String getColA() {
            return colA;
        }

        public void setColA(String colA) {
            this.colA = colA;
        }

        public String getColB() {
            return colB;
        }

        public void setColB(String colB) {
            this.colB = colB;
        }

        public String getOutput() {
            return output;
        }

        public String getOutModel() {
            return outModel;
        }

        public void setOutModel(String outModel) {
            this.outModel = outModel;
        }

        public void setOutput(String output) {
            this.output = output;
        }

        public String getIsOne() {
            return isOne;
        }

        public void setIsOne(String isOne) {
            this.isOne = isOne;
        }
    }



}
